package com.saifan.wyy_ov.ui.communitylife;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.data.bean.ColletionRequestBean;
import com.saifan.wyy_ov.data.bean.PermissionsBean;
import com.saifan.wyy_ov.data.bean.RentalBean;
import com.saifan.wyy_ov.data.bean.RequestBean;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.onlishop.PromotionDetailsActivity;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.zoomimage.ZoomImageActivity;
import com.saifan.wyy_ov.utils.CallPhoneUtil;
import com.saifan.wyy_ov.utils.PriceUtils;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.lightsky.infiniteindicator.InfiniteIndicatorLayout;
import cn.lightsky.infiniteindicator.slideview.BaseSliderView;
import cn.lightsky.infiniteindicator.slideview.DefaultSliderView;

/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-6-3 13:43:44
 * @descrption 租售信息详情
 */

public class RentalinfoItemActivity extends BaseActivity implements BaseSliderView.OnSliderClickListener {
    private Toolbar toolbar;
    private InfiniteIndicatorLayout slider;
    private TextView CZCSBT;
    private TextView CZCSJE;
    private TextView unit;
    private TextView CZCSHXMC;
    private TextView CZCSCZLX;
    private TextView CZCSFBSJ;
    private TextView CZCSWYLXMC;
    private TextView CZCSJZMJ;
    private TextView CZCSDZ;
    private TextView CZCSLXR;
    private TextView CZCSLXDH;
    private TextView CZCSXXQK;
    private ArrayList<String> urls = new ArrayList<>();


    private RentalBean rentalBean;
    RoomInfoBean roomInfoBean;
    private Boolean isSFSC = false;
    private ImageView collect;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                collect.setImageResource(R.drawable.collect_succeed);

            } else {

                collect.setClickable(true);


            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rentalBean = (RentalBean) getIntent().getSerializableExtra("data");
        roomInfoBean = getRoomInfoBean();
        setContentView();
    }


    public void setContentView() {
        setContentView(R.layout.activity_rentalinfo_item);
        this.collect = (ImageView) findViewById(R.id.collect);
        this.CZCSXXQK = (TextView) findViewById(R.id.CZCS_XXQK);
        this.CZCSLXDH = (TextView) findViewById(R.id.CZCS_LXDH);
        this.CZCSLXR = (TextView) findViewById(R.id.CZCS_LXR);
        this.CZCSDZ = (TextView) findViewById(R.id.CZCS_DZ);
        this.CZCSJZMJ = (TextView) findViewById(R.id.CZCS_JZMJ);
        this.CZCSWYLXMC = (TextView) findViewById(R.id.CZCS_WYLXMC);
        this.CZCSFBSJ = (TextView) findViewById(R.id.CZCS_FBSJ);
        this.CZCSCZLX = (TextView) findViewById(R.id.CZCS_CZLX);
        this.CZCSHXMC = (TextView) findViewById(R.id.CZCS_HXMC);
        this.unit = (TextView) findViewById(R.id.unit);
        this.CZCSJE = (TextView) findViewById(R.id.CZCS_JE);
        this.CZCSBT = (TextView) findViewById(R.id.CZCS_BT);
        this.slider = (InfiniteIndicatorLayout) findViewById(R.id.slider);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        if (rentalBean != null) {
            if (rentalBean.getCZCS_LX() == 1) {
                setTitle("租房详情");
            } else {
                setTitle("售房详情");
            }
            if (!StringUtil.isNullOrEmpty(rentalBean.getCZCS_TPLJ())) {
                urls = StringUtil.getArrayListStringByString(rentalBean.getCZCS_TPLJ(), ",");
                if (urls.size() > 0) {
                    for (int i = 0; i < urls.size(); i++) {
                        DefaultSliderView textSliderView = new DefaultSliderView(this);
                        textSliderView.image(Api.getUrlIp()  + urls.get(i)).showImageResForError(R.drawable.pic_load_fail).setScaleType(BaseSliderView.ScaleType.CenterCrop).setOnSliderClickListener(this);
                        if (textSliderView.getBundle() != null) {
                            textSliderView.getBundle().putInt("index", i);
                        }
                        slider.addSlider(textSliderView);
                    }
                    slider.setIndicatorPosition(InfiniteIndicatorLayout.IndicatorPosition.Center_Bottom);
                    if (urls.size() > 1)
                        slider.startAutoScroll(10000);
                    else {
                        slider.stopAutoScroll();
                        slider.setInfinite(false);
                    }


                }
            } else {
                DefaultSliderView textSliderView = new DefaultSliderView(this);
                textSliderView.image(R.drawable.pic_none).showImageResForEmpty(R.drawable.pic_none).setScaleType(BaseSliderView.ScaleType.CenterCrop);
                slider.addSlider(textSliderView);
                slider.setInfinite(false);


            }
            this.CZCSXXQK.setText(StringUtil.returnShow(rentalBean.getCZCS_XXQK()));
            this.CZCSLXDH.setText(StringUtil.returnShow(rentalBean.getCZCS_LXDH()));
            this.CZCSLXR.setText(StringUtil.returnShow(rentalBean.getCZCS_LXR()));
            this.CZCSDZ.setText("  " + StringUtil.returnShow(rentalBean.getCZCS_DZ()));
            this.CZCSJZMJ.setText(rentalBean.getCZCS_JZMJ() + "");
            this.CZCSWYLXMC.setText(StringUtil.returnShow(rentalBean.getCZCS_WYLXMC()));
            this.CZCSFBSJ.setText(StringUtil.returnShow(rentalBean.getCZCS_FBSJ()));
            this.CZCSCZLX.setText(StringUtil.returnShow(rentalBean.getCZCS_CZLX()));
            this.CZCSHXMC.setText(StringUtil.returnShow(rentalBean.getCZCS_HXMC()));
            if (rentalBean.getCZCS_LX() == 1) {
                this.unit.setText("元/月");
            } else {
                this.unit.setText("元/" + getString(R.string.m2));

            }
            this.CZCSJE.setText(PriceUtils.getPrice(rentalBean.getCZCS_JE()) + "");
            this.CZCSBT.setText(StringUtil.returnShow(rentalBean.getCZCS_BT()));


            collect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getRoomInfoBean().getUserType() == 2){
                        for (PermissionsBean permissionsBean : getPermissions()){
                            if (permissionsBean.getYKQX_GNMC().equals("租售信息")){
                                collection();
                                return;
                            }
                        }
                        ToastUtil.showToast(RentalinfoItemActivity.this, "您的权限不能进行此操作");
                        return;
                    } else if (getRoomInfoBean().getUserType() == 3){
                        ToastUtil.showToast(RentalinfoItemActivity.this, "您的权限不能进行此操作");
                        return;
                    }


                    collection();

                }
            });
        }


    }


    @Override
    protected void onStart() {
        super.onStart();
        action_IsCollection();
    }

    @Override
    protected void onPause() {
        super.onPause();
        slider.stopAutoScroll();

    }


    private void collection() {
        collect.setClickable(false);
        ColletionRequestBean colletionRequestBean = new ColletionRequestBean();
        colletionRequestBean.setXMBS(roomInfoBean.getXMBS());
        colletionRequestBean.setWDSC_KHWJ(roomInfoBean.getFKGX_ZJ());
        colletionRequestBean.setWDSC_MKID(rentalBean.getCZCS_ZJ());
        colletionRequestBean.setWDSC_LX(2);

        if (isSFSC) {
            new GetData().getDataJson(this, Api.Collection.CANCEL_COLLECTION, colletionRequestBean, getString(R.string.wait), new ResponseData() {
                @Override
                public void onSuccess(String json) {
                    isSFSC = false;
                    collect.setImageResource(R.drawable.collect_abolish);
                    mHandler.sendEmptyMessageDelayed(0, 3000);
                }

                @Override
                public void onFailed(String str) {
                    mHandler.sendEmptyMessageDelayed(0, 3000);
                }
            });

        } else {
            new GetData().getDataJson(this, Api.Collection.COLLECTION, colletionRequestBean, getString(R.string.wait), new ResponseData() {
                @Override
                public void onSuccess(String json) {
                    isSFSC = true;
                    collect.setImageResource(R.drawable.collect_succeed);
                    mHandler.sendEmptyMessageDelayed(0, 3000);
                    ;
                }

                @Override
                public void onFailed(String str) {
                    mHandler.sendEmptyMessageDelayed(0, 3000);
                }
            });

        }

    }

    private void action_IsCollection() {

        RequestBean requestBean = new RequestBean();
        requestBean.setXMBS(roomInfoBean.getXMBS());
        requestBean.setWDSC_MKID(rentalBean.getCZCS_ZJ());
        //2== 租售信息收藏
        requestBean.setWDSC_LX(2);
        requestBean.setWDSC_KHWJ(roomInfoBean.getWYKHDA_ZJ());

        GetData getData = new GetData();
        collect.setClickable(false);

        getData.getDataJson(this, Api.RentalInfo.IS_COLLECTION, requestBean, "", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                collect.setClickable(true);

                try {
                    JSONArray jsonArray = new JSONArray(json);
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    isSFSC = jsonObject.getBoolean("SFSC");
                    if (isSFSC) {
                        mHandler.sendEmptyMessage(1);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(String str) {
                collect.setClickable(true);
            }
        });

    }

    @Override
    public void onSliderClick(BaseSliderView baseSliderView) {
        Intent intent = new Intent(this, ZoomImageActivity.class);
        int position = baseSliderView.getBundle().getInt("index");
        intent.putExtra("position", position);
        intent.putStringArrayListExtra("img", urls);
        startActivity(intent);

    }

    // 联系买家
    public void call(View v) {
        if (!StringUtil.isNullOrEmpty(rentalBean.getCZCS_LXDH())) {



            if (Build.VERSION.SDK_INT >= 23) {

                int checkCallPhonePermission = ContextCompat.checkSelfPermission( this, Manifest.permission.CALL_PHONE);
                if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(RentalinfoItemActivity.this, new String[]{Manifest.permission.CALL_PHONE}, CALL_PHONE);
                    return;
                } else {
                    CallPhoneUtil.callPhone(RentalinfoItemActivity.this, rentalBean.getCZCS_LXDH());


                }
            } else {

                CallPhoneUtil.callPhone(RentalinfoItemActivity.this, rentalBean.getCZCS_LXDH());

            }
        }



    }



    private static final int CALL_PHONE = 123;
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                CallPhoneUtil.callPhone(RentalinfoItemActivity.this, rentalBean.getCZCS_LXDH());


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用拨打电话权限", Toast.LENGTH_SHORT)
                        .show();

            }
        }

    }

}
